import java.io.*;
import java.util.*;

public class MovieTicketSystem {
  // 当前登录用户
  private static User currentUser = null;
  private static Scanner scanner = new Scanner(System.in);

  public static void main(String[] args) {
      // 加载数据
      DataManager.loadData();

      // 显示初始账户信息
      System.out.println("\n=== 初始账户信息 ===");
      System.out.println("系统管理员: admin/admin123");
      System.out.println("售票员: sales1/sales123");
      System.out.println("店长: manager1/manager123");
      System.out.println("===================");

      // 显示主菜单
      showMainMenu();
  }

  // 主菜单
  private static void showMainMenu() {
      while (true) {
          System.out.println("\n=== 电影票务系统 ===");
          System.out.println("1. 用户登录");
          System.out.println("2. 用户注册");
          System.out.println("3. 退出系统");
          System.out.print("请选择: ");

          int choice = getIntInput();

          switch (choice) {
              case 1:
                  login();
                  break;
              case 2:
                  register();
                  break;
              case 3:
                  DataManager.saveData();
                  System.out.println("感谢使用，再见！");
                  System.exit(0);
              default:
                  System.out.println("无效选择，请重新输入！");
          }
      }
  }

  // 用户登录
  private static void login() {
      System.out.print("请输入用户名: ");
      String username = scanner.nextLine();
      System.out.print("请输入密码: ");
      String password = scanner.nextLine();

      for (User user : DataManager.users) {
          if (user.username.equals(username) && user.password.equals(DataManager.hashPassword(password))) {
              currentUser = user;
              System.out.println("登录成功！当前角色: " + user.role.getDescription());
              showUserMenu();
              return;
          }
      }
      System.out.println("用户名或密码错误！");
  }

  // 用户注册
  private static void register() {
      System.out.print("请输入用户名: ");
      String username = scanner.nextLine();

      // 检查用户名是否已存在
      for (User user : DataManager.users) {
          if (user.username.equals(username)) {
              System.out.println("用户名已存在！");
              return;
          }
      }

      System.out.print("请输入密码: ");
      String password = scanner.nextLine();
      System.out.print("请输入姓名: ");
      String name = scanner.nextLine();
      System.out.print("请输入电话: ");
      String phone = scanner.nextLine();
      System.out.print("请输入邮箱: ");
      String email = scanner.nextLine();

      User newUser = new User(DataManager.users.size() + 1, username, DataManager.hashPassword(password), 
                            name, phone, email, UserRole.CUSTOMER);
      DataManager.users.add(newUser);
      DataManager.saveData();
      System.out.println("注册成功！");
  }

  // 用户菜单
  private static void showUserMenu() {
      while (currentUser != null) {
          System.out.println("\n=== 用户菜单 (" + currentUser.role.getDescription() + ") ===");
          System.out.println("1. 个人信息管理");
          System.out.println("2. 影片信息查询");

          // 普通用户和售票员共有的功能
          if (currentUser.role == UserRole.CUSTOMER || currentUser.role == UserRole.SALES 
              || currentUser.role == UserRole.MANAGER || currentUser.role == UserRole.ADMIN) {
              System.out.println("3. 座位预订与购票");
              System.out.println("4. 订单管理");
          }

          // 售票员、店长和管理员的功能
          if (currentUser.role == UserRole.SALES || currentUser.role == UserRole.MANAGER 
              || currentUser.role == UserRole.ADMIN) {
              System.out.println("5. 排片管理");
              System.out.println("6. 座位管理");
          }

          // 店长和管理员的功能
          if (currentUser.role == UserRole.MANAGER || currentUser.role == UserRole.ADMIN) {
              System.out.println("7. 销售数据统计");
          }

          // 管理员特有功能
          if (currentUser.role == UserRole.ADMIN) {
              System.out.println("8. 系统维护");
              System.out.println("9. 反馈处理");
              System.out.println("10. 用户管理");
          }

          System.out.println("0. 退出登录");
          System.out.print("请选择: ");

          int choice = getIntInput();

          switch (choice) {
              case 1:
                  manageProfile();
                  break;
              case 2:
                  queryMovies();
                  break;
              case 3:
                  if (currentUser.role == UserRole.CUSTOMER || currentUser.role == UserRole.SALES 
                      || currentUser.role == UserRole.MANAGER || currentUser.role == UserRole.ADMIN) {
                      bookTickets();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 4:
                  if (currentUser.role == UserRole.CUSTOMER || currentUser.role == UserRole.SALES 
                      || currentUser.role == UserRole.MANAGER || currentUser.role == UserRole.ADMIN) {
                      manageOrders();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 5:
                  if (currentUser.role == UserRole.SALES || currentUser.role == UserRole.MANAGER 
                      || currentUser.role == UserRole.ADMIN) {
                      manageSchedules();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 6:
                  if (currentUser.role == UserRole.SALES || currentUser.role == UserRole.MANAGER 
                      || currentUser.role == UserRole.ADMIN) {
                      manageSeats();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 7:
                  if (currentUser.role == UserRole.MANAGER || currentUser.role == UserRole.ADMIN) {
                      viewSalesData();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 8:
                  if (currentUser.role == UserRole.ADMIN) {
                      systemMaintenance();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 9:
                  if (currentUser.role == UserRole.ADMIN) {
                      manageFeedbacks();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 10:
                  if (currentUser.role == UserRole.ADMIN) {
                      manageUsers();
                  } else {
                      System.out.println("无效选择，请重新输入！");
                  }
                  break;
              case 0:
                  currentUser = null;
                  System.out.println("已退出登录");
                  return;
              default:
                  System.out.println("无效选择，请重新输入！");
          }
      }
  }

  // 个人信息管理
  private static void manageProfile() {
      System.out.println("\n=== 个人信息 ===");
      System.out.println("用户名: " + currentUser.username);
      System.out.println("姓名: " + currentUser.name);
      System.out.println("电话: " + currentUser.phone);
      System.out.println("邮箱: " + currentUser.email);
      System.out.println("角色: " + currentUser.role.getDescription());

      System.out.println("\n1. 修改信息");
      System.out.println("2. 修改密码");
      System.out.println("3. 提交反馈(仅普通用户)");
      System.out.println("4. 返回");
      System.out.print("请选择: ");

      int choice = getIntInput();

      if (choice == 1) {
          System.out.print("请输入新姓名: ");
          String name = scanner.nextLine();
          System.out.print("请输入新电话: ");
          String phone = scanner.nextLine();
          System.out.print("请输入新邮箱: ");
          String email = scanner.nextLine();

          currentUser.name = name;
          currentUser.phone = phone;
          currentUser.email = email;
          DataManager.saveData();
          System.out.println("信息更新成功！");
      } else if (choice == 2) {
          System.out.print("请输入当前密码: ");
          String currentPassword = scanner.nextLine();
          if (!currentUser.password.equals(DataManager.hashPassword(currentPassword))) {
              System.out.println("当前密码错误！");
              return;
          }
          System.out.print("请输入新密码: ");
          String newPassword = scanner.nextLine();
          System.out.print("请确认新密码: ");
          String confirmPassword = scanner.nextLine();

          if (!newPassword.equals(confirmPassword)) {
              System.out.println("两次输入的密码不一致！");
              return;
          }

          currentUser.password = DataManager.hashPassword(newPassword);
          DataManager.saveData();
          System.out.println("密码修改成功！");
      } else if (choice == 3 && currentUser.role == UserRole.CUSTOMER) {
          System.out.print("请输入反馈内容: ");
          String content = scanner.nextLine();
          DataManager.feedbacks.add(new Feedback(DataManager.feedbacks.size() + 1, currentUser.id, content, new Date(), "待处理"));
          DataManager.saveData();
          System.out.println("反馈提交成功！");
      }
  }

  // 影片信息查询
  private static void queryMovies() {
      System.out.println("\n=== 影片列表 ===");
      for (int i = 0; i < DataManager.movies.size(); i++) {
          Movie movie = DataManager.movies.get(i);
          System.out.println((i + 1) + ". " + movie.title + " (" + movie.director + ")");
      }

      System.out.print("\n输入影片编号查看详情(0返回): ");
      int choice = getIntInput();

      if (choice > 0 && choice <= DataManager.movies.size()) {
          Movie movie = DataManager.movies.get(choice - 1);
          System.out.println("\n=== 影片详情 ===");
          System.out.println("片名: " + movie.title);
          System.out.println("导演: " + movie.director);
          System.out.println("演员: " + movie.actors);
          System.out.println("时长: " + movie.duration + "分钟");
          System.out.println("简介: " + movie.description);
          System.out.println("票价: ¥" + movie.price);

          // 显示排片信息
          System.out.println("\n=== 排片信息 ===");
          List<Schedule> movieSchedules = DataManager.getSchedulesByMovieId(movie.id);
          if (movieSchedules.isEmpty()) {
              System.out.println("暂无排片信息");
          } else {
              for (Schedule schedule : movieSchedules) {
                  System.out.println("场次ID: " + schedule.id + ", 放映时间: " + schedule.startTime + 
                                   " - " + schedule.endTime + ", 影厅: " + schedule.hall);
              }
          }

          System.out.print("\n按任意键返回...");
          scanner.nextLine();
      }
  }

  // 座位预订与购票
  private static void bookTickets() {
      System.out.println("\n=== 选择影片 ===");
      for (int i = 0; i < DataManager.movies.size(); i++) {
          Movie movie = DataManager.movies.get(i);
          System.out.println((i + 1) + ". " + movie.title);
      }

      System.out.print("\n选择影片(0返回): ");
      int movieChoice = getIntInput();

      if (movieChoice > 0 && movieChoice <= DataManager.movies.size()) {
          Movie selectedMovie = DataManager.movies.get(movieChoice - 1);

          // 显示该影片的排片
          List<Schedule> movieSchedules = DataManager.getSchedulesByMovieId(selectedMovie.id);
          if (movieSchedules.isEmpty()) {
              System.out.println("该影片暂无排片！");
              return;
          }

          System.out.println("\n=== 选择场次 ===");
          for (int i = 0; i < movieSchedules.size(); i++) {
              Schedule schedule = movieSchedules.get(i);
              System.out.println((i + 1) + ". 场次ID: " + schedule.id + 
                               ", 时间: " + schedule.startTime + " - " + schedule.endTime + 
                               ", 影厅: " + schedule.hall);
          }

          System.out.print("\n选择场次(0返回): ");
          int scheduleChoice = getIntInput();

          if (scheduleChoice > 0 && scheduleChoice <= movieSchedules.size()) {
              Schedule selectedSchedule = movieSchedules.get(scheduleChoice - 1);

              System.out.println("\n=== 座位选择 ===");
              System.out.println("影片: " + selectedMovie.title);
              System.out.println("场次: " + selectedSchedule.startTime + " - " + selectedSchedule.endTime);
              System.out.println("影厅: " + selectedSchedule.hall);
              System.out.println("票价: ¥" + selectedMovie.price);
              displaySeats(selectedSchedule.id);

              System.out.print("输入座位行号: ");
              int row = getIntInput();
              System.out.print("输入座位列号: ");
              int col = getIntInput();

              // 查找座位
              Seat seat = DataManager.findSeat(selectedSchedule.id, row, col);
              if (seat == null || !seat.available) {
                  System.out.println("该座位不可用！");
                  return;
              }

              // 创建订单
              int userId = currentUser.role == UserRole.CUSTOMER ? currentUser.id : 0; // 售票员代为购票时用户ID为0
              Order newOrder = new Order(DataManager.orders.size() + 1, userId, selectedMovie.id, 
                                       selectedSchedule.id, seat.id, new Date(), 
                                       selectedMovie.price, "已完成");
              DataManager.orders.add(newOrder);
              seat.available = false; // 标记座位为已预订
              DataManager.saveData();
              System.out.println("购票成功！订单号: " + newOrder.id);
          }
      }
  }

  // 订单管理
  private static void manageOrders() {
      List<Order> userOrders = new ArrayList<>();
      if (currentUser.role == UserRole.CUSTOMER) {
          // 普通用户只能查看自己的订单
          for (Order order : DataManager.orders) {
              if (order.userId == currentUser.id) {
                  userOrders.add(order);
              }
          }
      } else {
          // 工作人员可以查看所有订单
          userOrders.addAll(DataManager.orders);
      }

      System.out.println("\n=== 订单列表 ===");
      if (userOrders.isEmpty()) {
          System.out.println("暂无订单");
          return;
      }

      for (int i = 0; i < userOrders.size(); i++) {
          Order order = userOrders.get(i);
          Movie movie = DataManager.getMovieById(order.movieId);
          Schedule schedule = DataManager.getScheduleById(order.scheduleId);
          Seat seat = DataManager.getSeatById(order.seatId);
          String userName = order.userId == 0 ? "线下购票" : DataManager.getUserById(order.userId).name;

          System.out.println((i + 1) + ". 订单号: " + order.id + 
                           ", 影片: " + movie.title + 
                           ", 场次: " + schedule.startTime + 
                           ", 座位: " + seat.row + "排" + seat.col + "座" +
                           ", 价格: ¥" + order.totalPrice + 
                           ", 状态: " + order.status +
                           ", 用户: " + userName);
      }

      System.out.print("\n选择订单进行操作(0返回): ");
      int orderChoice = getIntInput();

      if (orderChoice > 0 && orderChoice <= userOrders.size()) {
          Order selectedOrder = userOrders.get(orderChoice - 1);

          System.out.println("\n1. 查看详情");
          if ("已完成".equals(selectedOrder.status)) {
              System.out.println("2. 退票");
          }
          System.out.println("3. 返回");
          System.out.print("请选择: ");

          int action = getIntInput();

          if (action == 1) {
              // 显示订单详情
              Movie movie = DataManager.getMovieById(selectedOrder.movieId);
              Schedule schedule = DataManager.getScheduleById(selectedOrder.scheduleId);
              Seat seat = DataManager.getSeatById(selectedOrder.seatId);
              String userName = selectedOrder.userId == 0 ? "线下购票" : DataManager.getUserById(selectedOrder.userId).name;

              System.out.println("\n=== 订单详情 ===");
              System.out.println("订单号: " + selectedOrder.id);
              System.out.println("影片: " + movie.title);
              System.out.println("场次: " + schedule.startTime + " - " + schedule.endTime);
              System.out.println("影厅: " + schedule.hall);
              System.out.println("座位: " + seat.row + "排" + seat.col + "座");
              System.out.println("价格: ¥" + selectedOrder.totalPrice);
              System.out.println("状态: " + selectedOrder.status);
              System.out.println("下单时间: " + selectedOrder.orderTime);
              System.out.println("用户: " + userName);

              System.out.print("\n按任意键返回...");
              scanner.nextLine();
          } else if (action == 2 && "已完成".equals(selectedOrder.status)) {
              Seat seat = DataManager.getSeatById(selectedOrder.seatId);
              seat.available = true; // 释放座位
              selectedOrder.status = "已退票";
              DataManager.saveData();
              System.out.println("退票成功！");
          }
      }
  }

  // 排片管理
  private static void manageSchedules() {
      System.out.println("\n=== 排片管理 ===");
      System.out.println("1. 添加排片");
      System.out.println("2. 查询排片");
      System.out.println("3. 删除排片");
      System.out.println("4. 返回");
      System.out.print("请选择: ");

      int choice = getIntInput();

      switch (choice) {
          case 1:
              addSchedule();
              break;
          case 2:
              querySchedules();
              break;
          case 3:
              deleteSchedule();
              break;
          case 4:
              return;
          default:
              System.out.println("无效选择，请重新输入！");
      }
  }

  // 添加排片
  private static void addSchedule() {
      System.out.println("\n=== 添加排片 ===");

      // 显示电影列表
      System.out.println("可选电影:");
      for (int i = 0; i < DataManager.movies.size(); i++) {
          System.out.println((i + 1) + ". " + DataManager.movies.get(i).title);
      }

      System.out.print("选择电影(0返回): ");
      int movieChoice = getIntInput();
      if (movieChoice == 0) return;
      if (movieChoice < 1 || movieChoice > DataManager.movies.size()) {
          System.out.println("无效选择！");
          return;
      }

      Movie selectedMovie = DataManager.movies.get(movieChoice - 1);

      System.out.print("输入开始时间(格式: yyyy-MM-dd HH:mm): ");
      String startTimeStr = scanner.nextLine();
      Date startTime = DataManager.parseDate(startTimeStr);
      if (startTime == null) {
          System.out.println("时间格式错误！");
          return;
      }

      // 计算结束时间（开始时间+电影时长）
      Calendar cal = Calendar.getInstance();
      cal.setTime(startTime);
      cal.add(Calendar.MINUTE, selectedMovie.duration);
      Date endTime = cal.getTime();

      System.out.print("输入影厅: ");
      String hall = scanner.nextLine();

      // 创建排片
      Schedule newSchedule = new Schedule(DataManager.schedules.size() + 1, selectedMovie.id, 
                                        startTime, endTime, hall);
      DataManager.schedules.add(newSchedule);

      // 为该排片创建座位
      for (int row = 1; row <= 5; row++) {
          for (int col = 1; col <= 10; col++) {
              DataManager.seats.add(new Seat(DataManager.seats.size() + 1, row, col, true, newSchedule.id));
          }
      }

      DataManager.saveData();
      System.out.println("排片添加成功！");
  }

  // 查询排片
  private static void querySchedules() {
      System.out.println("\n=== 排片查询 ===");
      System.out.println("1. 按电影查询");
      System.out.println("2. 查询所有排片");
      System.out.println("3. 返回");
      System.out.print("请选择: ");

      int choice = getIntInput();

      switch (choice) {
          case 1:
              querySchedulesByMovie();
              break;
          case 2:
              listAllSchedules();
              break;
          case 3:
              return;
          default:
              System.out.println("无效选择，请重新输入！");
      }
  }

  // 按电影查询排片
  private static void querySchedulesByMovie() {
      System.out.println("\n=== 按电影查询排片 ===");
      System.out.println("可选电影:");
      for (int i = 0; i < DataManager.movies.size(); i++) {
          System.out.println((i + 1) + ". " + DataManager.movies.get(i).title);
      }

      System.out.print("选择电影(0返回): ");
      int movieChoice = getIntInput();
      if (movieChoice == 0) return;
      if (movieChoice < 1 || movieChoice > DataManager.movies.size()) {
          System.out.println("无效选择！");
          return;
      }

      Movie selectedMovie = DataManager.movies.get(movieChoice - 1);
      List<Schedule> movieSchedules = DataManager.getSchedulesByMovieId(selectedMovie.id);

      System.out.println("\n=== " + selectedMovie.title + " 排片信息 ===");
      if (movieSchedules.isEmpty()) {
          System.out.println("暂无排片信息");
      } else {
          for (Schedule schedule : movieSchedules) {
              System.out.println("场次ID: " + schedule.id + 
                               ", 时间: " + schedule.startTime + " - " + schedule.endTime + 
                               ", 影厅: " + schedule.hall);
          }
      }

      System.out.print("\n按任意键返回...");
      scanner.nextLine();
  }

  // 列出所有排片
  private static void listAllSchedules() {
      System.out.println("\n=== 所有排片信息 ===");
      if (DataManager.schedules.isEmpty()) {
          System.out.println("暂无排片信息");
          return;
      }

      for (Schedule schedule : DataManager.schedules) {
          Movie movie = DataManager.getMovieById(schedule.movieId);
          System.out.println("场次ID: " + schedule.id + 
                           ", 影片: " + movie.title + 
                           ", 时间: " + schedule.startTime + " - " + schedule.endTime + 
                           ", 影厅: " + schedule.hall);
      }

      System.out.print("\n按任意键返回...");
      scanner.nextLine();
  }

  // 删除排片
  private static void deleteSchedule() {
      System.out.println("\n=== 删除排片 ===");
      listAllSchedules();

      System.out.print("\n输入要删除的场次ID(0返回): ");
      int scheduleId = getIntInput();
      if (scheduleId == 0) return;

      Schedule scheduleToDelete = DataManager.getScheduleById(scheduleId);
      if (scheduleToDelete == null) {
          System.out.println("无效的场次ID！");
          return;
      }

      // 检查是否有订单关联该排片
      boolean hasOrders = DataManager.orders.stream().anyMatch(o -> o.scheduleId == scheduleId);
      if (hasOrders) {
          System.out.println("该场次已有订单，不能删除！");
          return;
      }

      // 删除排片和关联的座位
      DataManager.schedules.removeIf(s -> s.id == scheduleId);
      DataManager.seats.removeIf(s -> s.scheduleId == scheduleId);
      DataManager.saveData();
      System.out.println("排片删除成功！");
  }

  // 座位管理
  private static void manageSeats() {
      System.out.println("\n=== 座位管理 ===");
      listAllSchedules();

      System.out.print("\n输入场次ID查看座位(0返回): ");
      int scheduleId = getIntInput();
      if (scheduleId == 0) return;

      Schedule schedule = DataManager.getScheduleById(scheduleId);
      if (schedule == null) {
          System.out.println("无效的场次ID！");
          return;
      }

      Movie movie = DataManager.getMovieById(schedule.movieId);
      System.out.println("\n=== 座位管理 ===");
      System.out.println("影片: " + movie.title);
      System.out.println("场次: " + schedule.startTime + " - " + schedule.endTime);
      System.out.println("影厅: " + schedule.hall);

      displaySeats(scheduleId);

      System.out.println("\n1. 设置座位状态");
      System.out.println("2. 返回");
      System.out.print("请选择: ");

      int choice = getIntInput();
      if (choice == 1) {
          setSeatStatus(scheduleId);
      }
  }

  // 设置座位状态
  private static void setSeatStatus(int scheduleId) {
      System.out.print("输入座位行号: ");
      int row = getIntInput();
      System.out.print("输入座位列号: ");
      int col = getIntInput();

      Seat seat = DataManager.findSeat(scheduleId, row, col);
      if (seat == null) {
      System.out.println("无效的座位！");
      return;
  }

  System.out.println("当前状态: " + (seat.available ? "可用" : "不可用"));
  System.out.println("1. 设置为可用");
  System.out.println("2. 设置为不可用");
  System.out.println("3. 取消");
  System.out.print("请选择: ");

  int choice = getIntInput();
  if (choice == 1) {
      seat.available = true;
      DataManager.saveData();
      System.out.println("座位状态已更新为可用");
  } else if (choice == 2) {
      seat.available = false;
      DataManager.saveData();
      System.out.println("座位状态已更新为不可用");
  }
}

// 销售数据统计
private static void viewSalesData() {
  System.out.println("\n=== 销售数据统计 ===");
  System.out.println("1. 按电影统计");
  System.out.println("2. 按日期统计");
  System.out.println("3. 返回");
  System.out.print("请选择: ");

  int choice = getIntInput();

  switch (choice) {
      case 1:
          salesByMovie();
          break;
      case 2:
          salesByDate();
          break;
      case 3:
          return;
      default:
          System.out.println("无效选择，请重新输入！");
  }
}

// 按电影统计销售数据
private static void salesByMovie() {
  System.out.println("\n=== 按电影统计销售数据 ===");

  Map<Integer, Double> movieSales = new HashMap<>();
  Map<Integer, Integer> movieTickets = new HashMap<>();

  for (Order order : DataManager.orders) {
      if ("已完成".equals(order.status)) {
          movieSales.merge(order.movieId, order.totalPrice, Double::sum);
          movieTickets.merge(order.movieId, 1, Integer::sum);
      }
  }

  if (movieSales.isEmpty()) {
      System.out.println("暂无销售数据");
      return;
  }

  System.out.println("电影\t\t售票数量\t销售金额");
  for (Map.Entry<Integer, Double> entry : movieSales.entrySet()) {
      Movie movie = DataManager.getMovieById(entry.getKey());
      int tickets = movieTickets.get(entry.getKey());
      System.out.printf("%s\t%d\t¥%.2f\n", movie.title, tickets, entry.getValue());
  }

  double totalSales = movieSales.values().stream().mapToDouble(Double::doubleValue).sum();
  int totalTickets = movieTickets.values().stream().mapToInt(Integer::intValue).sum();
  System.out.printf("\n总计: %d张票, ¥%.2f\n", totalTickets, totalSales);

  System.out.print("\n按任意键返回...");
  scanner.nextLine();
}

// 按日期统计销售数据
private static void salesByDate() {
  System.out.println("\n=== 按日期统计销售数据 ===");

  // 按日期分组统计
  Map<String, Double> dateSales = new TreeMap<>();
  Map<String, Integer> dateTickets = new TreeMap<>();

  for (Order order : DataManager.orders) {
      if ("已完成".equals(order.status)) {
          String dateStr = new java.text.SimpleDateFormat("yyyy-MM-dd").format(order.orderTime);
          dateSales.merge(dateStr, order.totalPrice, Double::sum);
          dateTickets.merge(dateStr, 1, Integer::sum);
      }
  }

  if (dateSales.isEmpty()) {
      System.out.println("暂无销售数据");
      return;
  }

  System.out.println("日期\t\t售票数量\t销售金额");
  for (Map.Entry<String, Double> entry : dateSales.entrySet()) {
      int tickets = dateTickets.get(entry.getKey());
      System.out.printf("%s\t%d\t¥%.2f\n", entry.getKey(), tickets, entry.getValue());
  }

  double totalSales = dateSales.values().stream().mapToDouble(Double::doubleValue).sum();
  int totalTickets = dateTickets.values().stream().mapToInt(Integer::intValue).sum();
  System.out.printf("\n总计: %d张票, ¥%.2f\n", totalTickets, totalSales);

  System.out.print("\n按任意键返回...");
  scanner.nextLine();
}

// 系统维护
private static void systemMaintenance() {
  System.out.println("\n=== 系统维护 ===");
  System.out.println("1. 备份数据");
  System.out.println("2. 恢复数据");
  System.out.println("3. 系统状态");
  System.out.println("4. 返回");
  System.out.print("请选择: ");

  int choice = getIntInput();

  switch (choice) {
      case 1:
          backupData();
          break;
      case 2:
          restoreData();
          break;
      case 3:
          systemStatus();
          break;
      case 4:
          return;
      default:
          System.out.println("无效选择，请重新输入！");
  }
}

// 备份数据
private static void backupData() {
  String backupFile = "movie_backup_" + new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".ser";
  try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(backupFile))) {
      oos.writeObject(DataManager.users);
      oos.writeObject(DataManager.movies);
      oos.writeObject(DataManager.seats);
      oos.writeObject(DataManager.orders);
      oos.writeObject(DataManager.feedbacks);
      oos.writeObject(DataManager.schedules);
      System.out.println("数据备份成功，保存为: " + backupFile);
  } catch (IOException e) {
      System.out.println("备份失败: " + e.getMessage());
  }
}

// 恢复数据
private static void restoreData() {
  System.out.println("当前目录下的备份文件:");
  File dir = new File(".");
  File[] files = dir.listFiles((d, name) -> name.startsWith("movie_backup_") && name.endsWith(".ser"));

  if (files == null || files.length == 0) {
      System.out.println("没有找到备份文件");
      return;
  }

  for (int i = 0; i < files.length; i++) {
      System.out.println((i + 1) + ". " + files[i].getName());
  }

  System.out.print("选择要恢复的备份文件(0取消): ");
  int choice = getIntInput();
  if (choice == 0) return;
  if (choice < 1 || choice > files.length) {
      System.out.println("无效选择");
      return;
  }

  File backupFile = files[choice - 1];
  System.out.print("确定要从 " + backupFile.getName() + " 恢复数据吗？(y/n): ");
  String confirm = scanner.nextLine();
  if (!confirm.equalsIgnoreCase("y")) {
      System.out.println("已取消恢复");
      return;
  }

  try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(backupFile))) {
      DataManager.users = (List<User>) ois.readObject();
      DataManager.movies = (List<Movie>) ois.readObject();
      DataManager.seats = (List<Seat>) ois.readObject();
      DataManager.orders = (List<Order>) ois.readObject();
      DataManager.feedbacks = (List<Feedback>) ois.readObject();
      DataManager.schedules = (List<Schedule>) ois.readObject();
      System.out.println("数据恢复成功！");
  } catch (IOException | ClassNotFoundException e) {
      System.out.println("恢复失败: " + e.getMessage());
  }
}

// 系统状态
private static void systemStatus() {
  System.out.println("\n=== 系统状态 ===");
  System.out.println("用户数量: " + DataManager.users.size());
  System.out.println("电影数量: " + DataManager.movies.size());
  System.out.println("排片数量: " + DataManager.schedules.size());
  System.out.println("座位数量: " + DataManager.seats.size());
  System.out.println("订单数量: " + DataManager.orders.size());
  System.out.println("反馈数量: " + DataManager.feedbacks.size());

  System.out.print("\n按任意键返回...");
  scanner.nextLine();
}

// 反馈处理
private static void manageFeedbacks() {
  System.out.println("\n=== 反馈处理 ===");

  List<Feedback> pendingFeedbacks = new ArrayList<>();
  for (Feedback feedback : DataManager.feedbacks) {
      if ("待处理".equals(feedback.status)) {
          pendingFeedbacks.add(feedback);
      }
  }

  if (pendingFeedbacks.isEmpty()) {
      System.out.println("暂无待处理反馈");
      return;
  }

  System.out.println("待处理反馈:");
  for (int i = 0; i < pendingFeedbacks.size(); i++) {
      Feedback feedback = pendingFeedbacks.get(i);
      User user = DataManager.getUserById(feedback.userId);
      System.out.println((i + 1) + ". ID: " + feedback.id + 
                       ", 用户: " + user.name + 
                       ", 时间: " + feedback.submitTime + 
                       ", 内容: " + feedback.content);
  }

  System.out.print("\n选择要处理的反馈(0返回): ");
  int choice = getIntInput();
  if (choice == 0) return;
  if (choice < 1 || choice > pendingFeedbacks.size()) {
      System.out.println("无效选择");
      return;
  }

  Feedback selectedFeedback = pendingFeedbacks.get(choice - 1);
  System.out.println("\n=== 反馈详情 ===");
  User user = DataManager.getUserById(selectedFeedback.userId);
  System.out.println("反馈ID: " + selectedFeedback.id);
  System.out.println("用户: " + user.name);
  System.out.println("时间: " + selectedFeedback.submitTime);
  System.out.println("内容: " + selectedFeedback.content);

  System.out.print("\n输入处理意见: ");
  String reply = scanner.nextLine();
  selectedFeedback.reply = reply;
  selectedFeedback.status = "已处理";
  selectedFeedback.processTime = new Date();
  selectedFeedback.processorId = currentUser.id;
  DataManager.saveData();
  System.out.println("反馈处理完成！");
}

// 用户管理
private static void manageUsers() {
  System.out.println("\n=== 用户管理 ===");
  System.out.println("1. 查看所有用户");
  System.out.println("2. 添加用户");
  System.out.println("3. 修改用户角色");
  System.out.println("4. 重置用户密码");
  System.out.println("5. 返回");
  System.out.print("请选择: ");

  int choice = getIntInput();

  switch (choice) {
      case 1:
          listAllUsers();
          break;
      case 2:
          addUser();
          break;
      case 3:
          changeUserRole();
          break;
      case 4:
          resetUserPassword();
          break;
      case 5:
          return;
      default:
          System.out.println("无效选择，请重新输入！");
  }
}

// 列出所有用户
private static void listAllUsers() {
  System.out.println("\n=== 所有用户 ===");
  System.out.println("ID\t用户名\t姓名\t角色");
  for (User user : DataManager.users) {
      System.out.println(user.id + "\t" + user.username + "\t" + user.name + "\t" + user.role.getDescription());
  }

  System.out.print("\n按任意键返回...");
  scanner.nextLine();
}

// 添加用户
private static void addUser() {
  System.out.println("\n=== 添加用户 ===");
  System.out.print("请输入用户名: ");
  String username = scanner.nextLine();

  // 检查用户名是否已存在
  for (User user : DataManager.users) {
      if (user.username.equals(username)) {
      System.out.println("用户名已存在！");
      return;
  }
}

System.out.print("请输入密码: ");
String password = scanner.nextLine();
System.out.print("请输入姓名: ");
String name = scanner.nextLine();
System.out.print("请输入电话: ");
String phone = scanner.nextLine();
System.out.print("请输入邮箱: ");
String email = scanner.nextLine();

System.out.println("选择角色:");
for (UserRole role : UserRole.values()) {
  System.out.println((role.ordinal() + 1) + ". " + role.getDescription());
}
System.out.print("请选择: ");
int roleChoice = getIntInput();
if (roleChoice < 1 || roleChoice > UserRole.values().length) {
  System.out.println("无效选择！");
  return;
}
UserRole role = UserRole.values()[roleChoice - 1];

User newUser = new User(DataManager.users.size() + 1, username, DataManager.hashPassword(password), 
                    name, phone, email, role);
DataManager.users.add(newUser);
DataManager.saveData();
System.out.println("用户添加成功！");
}

// 修改用户角色
private static void changeUserRole() {
  System.out.println("\n=== 修改用户角色 ===");
  listAllUsers();

  System.out.print("\n输入要修改的用户ID(0返回): ");
  int userId = getIntInput();
  if (userId == 0) return;

  User userToModify = DataManager.getUserById(userId);
  if (userToModify == null) {
      System.out.println("无效的用户ID！");
      return;
  }

  if (userToModify.role == UserRole.ADMIN) {
      System.out.println("不能修改系统管理员的角色！");
      return;
  }

  System.out.println("当前角色: " + userToModify.role.getDescription());
  System.out.println("选择新角色:");
  for (UserRole role : UserRole.values()) {
      if (role != UserRole.ADMIN) { // 不能将普通用户设置为管理员
          System.out.println((role.ordinal() + 1) + ". " + role.getDescription());
      }
  }
  System.out.print("请选择: ");
  int roleChoice = getIntInput();
  if (roleChoice < 1 || roleChoice >= UserRole.values().length) {
      System.out.println("无效选择！");
      return;
  }
  UserRole newRole = UserRole.values()[roleChoice - 1];

  userToModify.role = newRole;
  DataManager.saveData();
  System.out.println("用户角色修改成功！");
}

// 重置用户密码
private static void resetUserPassword() {
  System.out.println("\n=== 重置用户密码 ===");
  listAllUsers();

  System.out.print("\n输入要重置密码的用户ID(0返回): ");
  int userId = getIntInput();
  if (userId == 0) return;

  User userToReset = DataManager.getUserById(userId);
  if (userToReset == null) {
      System.out.println("无效的用户ID！");
      return;
  }

  System.out.print("输入新密码: ");
  String newPassword = scanner.nextLine();
  userToReset.password = DataManager.hashPassword(newPassword);
  DataManager.saveData();
  System.out.println("密码重置成功！");
}

// 显示座位图
private static void displaySeats(int scheduleId) {
  System.out.println("\n座位图（X表示已预订，O表示可用）:");
  System.out.println("  1 2 3 4 5 6 7 8 9 10");

  for (int row = 1; row <= 5; row++) {
      System.out.print(row + " ");
      for (int col = 1; col <= 10; col++) {
          Seat seat = DataManager.findSeat(scheduleId, row, col);
          System.out.print(seat != null && seat.available ? "O " : "X ");
      }
      System.out.println();
  }
}

// 获取整数输入
private static int getIntInput() {
  while (true) {
      try {
          int input = scanner.nextInt();
          scanner.nextLine(); // 消耗换行符
          return input;
      } catch (InputMismatchException e) {
          System.out.print("请输入有效数字: ");
          scanner.nextLine(); // 清除无效输入
      }
  }
}
}